package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.job.UpdateContractStatusJob;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author xjl
 * @date 2025-10-10
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private BedMapper bedMapper;


    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int apply(CheckInApplyDto dto) {
//CheckInApplyDto
        CheckInContractDto contractDto = dto.getCheckInContractDto();
        CheckInElderDto elderDto = dto.getCheckInElderDto();
        CheckInConfigDto inConfigDto = dto.getCheckInConfigDto();
        List<ElderFamilyDto> familyDtoList = dto.getElderFamilyDtoList();
        //校验老人是否已入住  如果已入住直接抛异常BaseException
//         根据老人身份证号+状态状态（0：禁用，1:启用  2:请假 3:退住中 4入住中 5已退住）  从老人表中查询
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, elderDto.getIdCardNo());
        queryWrapper.eq(Elder::getStatus, 4);
        Elder elder = elderMapper.selectOne(queryWrapper);
        if (elder != null) {
            throw new BaseException("该老人已入住");
        }

//更新床位的状态
        Long bedId = inConfigDto.getBedId();
        Bed bed = bedMapper.selectById(bedId);
        if (bed == null) {
            throw new BaseException("请选择正确的床位");
        }
        bed.setBedStatus(1);
        bedMapper.updateBed(bed);
//新增或更新老人elder
        elder = saveOrUpdateElder(elderDto, bed);
//新增合同信息  合同号要求： HT+18位数字，例：HT202501011012590001
        saveContract(contractDto, elder, inConfigDto);
//新增入住信息  老人家属信息存到remark字段中
        CheckIn checkIn = saveCheckInConfig(inConfigDto, elder, bed, familyDtoList);
//新增入住配置
        addCheckInConfig(checkIn, elder, contractDto, inConfigDto);
        return 1;
    }


    private void addCheckInConfig(CheckIn checkIn, Elder elder, CheckInContractDto contractDto, CheckInConfigDto inConfigDto) {
        CheckInConfig checkInConfig = new CheckInConfig();

        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfig.setNursingLevelId(inConfigDto.getNursingLevelId());
        checkInConfig.setNursingLevelName(checkIn.getNursingLevelName());
        checkInConfig.setFeeStartDate(inConfigDto.getFeeStartDate());
        checkInConfig.setFeeEndDate(inConfigDto.getFeeEndDate());
        checkInConfig.setDeposit(inConfigDto.getDeposit());
        checkInConfig.setNursingFee(inConfigDto.getNursingFee());
        checkInConfig.setBedFee(inConfigDto.getBedFee());
        checkInConfig.setInsurancePayment(inConfigDto.getInsurancePayment());
        checkInConfig.setGovernmentSubsidy(inConfigDto.getGovernmentSubsidy());
        checkInConfig.setOtherFees(inConfigDto.getOtherFees());
        checkInConfigMapper.insert(checkInConfig);
    }

    private void saveContract(CheckInContractDto contractDto, Elder elder, CheckInConfigDto inConfigDto) {
        Contract contract = new Contract();

        contract.setElderId(elder.getId());
        contract.setContractName(contractDto.getContractName());
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contract.setAgreementPath(contractDto.getAgreementPath());
        contract.setThirdPartyPhone(contractDto.getThirdPartyPhone());
        contract.setThirdPartyName(contractDto.getThirdPartyName());
        contract.setElderName(elder.getName());
        contract.setStartDate(inConfigDto.getStartDate());
        contract.setEndDate(inConfigDto.getEndDate());

        contract.setSignDate(contractDto.getSignDate());
        if (contractDto.getSignDate().isBefore(LocalDateTime.now())){
            contract.setStatus(1);
        }else {
            contract.setStatus(0);
        }
        contractMapper.insert(contract);

    }

    private CheckIn saveCheckInConfig(CheckInConfigDto inConfigDto, Elder elder, Bed bed, List<ElderFamilyDto> familyDtoList) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(inConfigDto.getStartDate());
        checkIn.setEndDate(inConfigDto.getEndDate());
        checkIn.setNursingLevelName(inConfigDto.getNursingLevelName());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0L);
        String jsonStr = JSONUtil.toJsonStr(familyDtoList);
        checkIn.setRemark(jsonStr);
        checkInMapper.insert(checkIn);
        return checkIn;

    }

    public Elder saveOrUpdateElder(CheckInElderDto elderDto, Bed bed) {
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, elderDto.getIdCardNo());
        Elder elder = elderMapper.selectOne(queryWrapper);
        if (elder == null) {
            elder = new Elder();
            elder.setName(elderDto.getName());
            elder.setImage(elderDto.getImage());
            elder.setIdCardNo(elderDto.getIdCardNo());
            elder.setSex(elderDto.getSex());
            elder.setStatus(4);
            elder.setPhone(elderDto.getPhone());
            elder.setBirthday(elderDto.getBirthday());
            elder.setAddress(elderDto.getAddress());
            elder.setIdCardNationalEmblemImg(elderDto.getIdCardNationalEmblemImg());
            elder.setIdCardPortraitImg(elderDto.getIdCardPortraitImg());
            elder.setBedNumber(bed.getBedNumber());
            elder.setBedId(bed.getId());
            elderMapper.insert(elder);
        } else {
            elder = new Elder();
            elder.setName(elderDto.getName());
            elder.setImage(elderDto.getImage());
            elder.setIdCardNo(elderDto.getIdCardNo());
            elder.setSex(elderDto.getSex());
            elder.setStatus(4);
            elder.setPhone(elderDto.getPhone());
            elder.setBirthday(elderDto.getBirthday());
            elder.setAddress(elderDto.getAddress());
            elder.setIdCardNationalEmblemImg(elderDto.getIdCardNationalEmblemImg());
            elder.setIdCardPortraitImg(elderDto.getIdCardPortraitImg());
            elder.setBedNumber(bed.getBedNumber());
            elder.setBedId(bed.getId());
            elderMapper.updateElder(elder);
        }
        return elder;
    }

    @Override
    public CheckInDetailVo selectAll(Long id) {
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        Elder elder = elderMapper.selectElderById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        checkInElderVo.setId(elder.getId());
        checkInElderVo.setName(elder.getName());
        checkInElderVo.setIdCardNo(elder.getIdCardNo());
        checkInElderVo.setBirthday(elder.getBirthday());
        checkInElderVo.setSex(elder.getSex());
        checkInElderVo.setPhone(elder.getPhone());
        checkInElderVo.setAddress(elder.getAddress());
        checkInElderVo.setImage(elder.getImage());
        checkInElderVo.setIdCardNationalEmblemImg(elder.getIdCardNationalEmblemImg());
        checkInElderVo.setIdCardPortraitImg(elder.getIdCardPortraitImg());
        int age = DateUtil.ageOfNow(elder.getBirthday());
        checkInElderVo.setAge(age);


        String remark = checkIn.getRemark();
        List<ElderFamilyVo> list = JSONUtil.toList(remark, ElderFamilyVo.class);
        LambdaQueryWrapper<CheckInConfig> queryWrapper1 =new LambdaQueryWrapper<>();
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        queryWrapper1.eq(CheckInConfig::getCheckInId,id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(queryWrapper1);

        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInConfigVo.setCheckInId(checkIn.getId());
        checkInConfigVo.setNursingLevelId(checkInConfig.getNursingLevelId());
        checkInConfigVo.setNursingLevelName(checkIn.getNursingLevelName());
        checkInConfigVo.setFeeStartDate(checkInConfig.getFeeStartDate());
        checkInConfigVo.setFeeEndDate(checkInConfig.getFeeEndDate());
        checkInConfigVo.setDeposit(checkInConfig.getDeposit());
        checkInConfigVo.setNursingFee(checkInConfig.getNursingFee());
        checkInConfigVo.setBedFee(checkInConfig.getBedFee());
        checkInConfigVo.setInsurancePayment(checkInConfig.getInsurancePayment());
        checkInConfigVo.setGovernmentSubsidy(checkInConfig.getGovernmentSubsidy());
        checkInConfigVo.setOtherFees(checkInConfig.getOtherFees());
        checkInConfigVo.setSortOrder(checkInConfig.getSortOrder());

        LambdaQueryWrapper<Contract> queryWrapper =new LambdaQueryWrapper<>();
        Contract contract1 = new Contract();
        queryWrapper.eq(Contract::getElderId,checkIn.getElderId());
        Contract contract = contractMapper.selectOne(queryWrapper);

        contract1.setElderId(elder.getId());
        contract1.setContractName(contract.getContractName());
        contract1.setContractNumber(contract.getContractNumber());
        contract1.setAgreementPath(contract.getAgreementPath());
        contract1.setThirdPartyPhone(contract.getThirdPartyPhone());
        contract1.setThirdPartyName(contract.getThirdPartyPhone());
        contract1.setElderName(contract.getElderName());
        contract1.setStartDate(contract.getStartDate());
        contract1.setEndDate(contract.getEndDate());
        contract1.setStatus(contract.getStatus());
        contract1.setSignDate(contract.getSignDate());
        contract1.setTerminationSubmitter(contract.getTerminationSubmitter());
        contract1.setTerminationDate(contract.getTerminationDate());
        contract1.setTerminationAgreementPath(contract.getTerminationAgreementPath());
        contract1.setSortOrder(contract.getSortOrder());
        contract1.setSearchValue(contract.getSearchValue());
        contract1.setCreateBy(contract.getCreateBy());
        contract1.setCreateTime(contract.getCreateTime());
        contract1.setUpdateBy(contract.getUpdateBy());
        contract1.setUpdateTime(contract.getUpdateTime());
        contract1.setRemark(contract.getRemark());
        contract1.setParams(contract.getParams());


        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setElderFamilyVoList(list);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contract);

        return checkInDetailVo;
    }
}


